package starlingui.component
{
	import com.imcrl.component.ILayoutable;
	import com.imcrl.component.PageList;
	import com.imcrl.component.itemRender.IListItemRender;
	import com.imcrl.core.IFactory;
	import com.imcrl.event.AdvListItemEvent;
	import com.imcrl.event.DragAndDropEvent;
	import com.imcrl.event.ListItemEvent;
	
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import starling.events.EventDispatcher;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	
	import starlingui.component.itemRender.IconItemRender;
	
	public class AdvPageList extends PageList
	{
		private var timer:Timer;

		public function AdvPageList(factory:IFactory)
		{
			timer=new Timer(500,2);
			timer.addEventListener(TimerEvent.TIMER_COMPLETE,shakeHandle);
			
			super(factory);
		}
		
		override protected function bindEnabled(item:IListItemRender,enabled:Boolean):void{
			if(item is EventDispatcher == false)return;
			super.bindEnabled(item,enabled);
			var eventDispatcher:IconItemRender=item as IconItemRender;
			if(enabled){
				eventDispatcher.addEventListener(DragAndDropEvent.DRAG_RECOGNIZED,dragStartHandle);
				eventDispatcher.addEventListener(TouchEvent.TOUCH, touchHandle);
			}else{
				eventDispatcher.addEventListener(DragAndDropEvent.DRAG_RECOGNIZED,dragStartHandle);
				eventDispatcher.removeEventListener(TouchEvent.TOUCH, touchHandle);
			}
		}
		
		private function dragStartHandle(event:DragAndDropEvent):void{
			if(this.hasEventListener(AdvListItemEvent.ITEM_DRAG_RECOGNIZED)){
				var e:AdvListItemEvent=new AdvListItemEvent(AdvListItemEvent.ITEM_DRAG_RECOGNIZED,event.dragInitiator as IListItemRender);
				this.dispatchEvent(e);
			}
		}
		
		
		/**
		 * 抖动效果; 
		 * @param event
		 * 
		 */		
		private function shakeHandle(event:TimerEvent):void{
			if(hasEventListener(ListItemEvent.SELECTED_SHAKE)){
				this.dispatchEvent(new ListItemEvent(ListItemEvent.SELECTED_SHAKE));
			}
		}
		
		/**
		 * 
		 * @param e
		 * 
		 */		
		private function touchHandle(e:TouchEvent):void{
			var touch:Touch = e.getTouch(this);
			
			this.selectedItem=e.target as IListItemRender;
			
			if (touch == null) return;
			switch(touch.phase){
				case TouchPhase.BEGAN :
					timer.reset();
					timer.start();
					break;
				case TouchPhase.MOVED :
				case TouchPhase.ENDED :
					timer.reset();
					break;
			}
		}
	}
}